<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1">
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">




  
  
  
  

  
    
    
  

  
    
      
    

    
  

  

  

  
    
      
    

    
  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Monda:300,300italic,400,400italic,700,700italic|Roboto Slab:300,300italic,400,400italic,700,700italic|PT Mono:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="Hexo, NexT">










<meta name="description" content="闭包的特性 函数嵌套函数 函数内部可以引用外部的参数和变量 参数和变量不会被垃圾回收制回收  闭包的定义及其优缺点闭包 是指有权访问另一个函数作用域中的变量的函数，创建闭包的最常见的方式就是在一个函数内创建另一个函数，通过另一个函数访问这个函数的局部变量 闭包的缺点就是常驻内存，会增大内存使用量，使用不当很容易造成内存泄露。 闭包是javascript语言的一大特点，主要应用闭包场合主要是为了：设">
<meta property="og:type" content="article">
<meta property="og:title" content="javascript之s闭包">
<meta property="og:url" content="http://blog.xiaowuzi.info/2013/04/08/javascript之闭包/index.html">
<meta property="og:site_name" content="小武子博客">
<meta property="og:description" content="闭包的特性 函数嵌套函数 函数内部可以引用外部的参数和变量 参数和变量不会被垃圾回收制回收  闭包的定义及其优缺点闭包 是指有权访问另一个函数作用域中的变量的函数，创建闭包的最常见的方式就是在一个函数内创建另一个函数，通过另一个函数访问这个函数的局部变量 闭包的缺点就是常驻内存，会增大内存使用量，使用不当很容易造成内存泄露。 闭包是javascript语言的一大特点，主要应用闭包场合主要是为了：设">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2018-04-08T03:31:46.827Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="javascript之s闭包">
<meta name="twitter:description" content="闭包的特性 函数嵌套函数 函数内部可以引用外部的参数和变量 参数和变量不会被垃圾回收制回收  闭包的定义及其优缺点闭包 是指有权访问另一个函数作用域中的变量的函数，创建闭包的最常见的方式就是在一个函数内创建另一个函数，通过另一个函数访问这个函数的局部变量 闭包的缺点就是常驻内存，会增大内存使用量，使用不当很容易造成内存泄露。 闭包是javascript语言的一大特点，主要应用闭包场合主要是为了：设">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://blog.xiaowuzi.info/2013/04/08/javascript之闭包/">





  <title>javascript之s闭包 | 小武子博客</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">小武子博客</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br>
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br>
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br>
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            归档
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://blog.xiaowuzi.info/2013/04/08/javascript之闭包/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Tony">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="小武子博客">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">javascript之s闭包</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2013-04-08T20:51:07+08:00">
                2013-04-08
              </time>
            

            

            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/javascript基础/" itemprop="url" rel="index">
                    <span itemprop="name">javascript基础</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h2 id="闭包的特性"><a href="#闭包的特性" class="headerlink" title="闭包的特性"></a>闭包的特性</h2><ol>
<li>函数嵌套函数</li>
<li>函数内部可以引用外部的参数和变量</li>
<li>参数和变量不会被垃圾回收制回收</li>
</ol>
<h2 id="闭包的定义及其优缺点"><a href="#闭包的定义及其优缺点" class="headerlink" title="闭包的定义及其优缺点"></a>闭包的定义及其优缺点</h2><p>闭包 是指有权访问另一个函数作用域中的变量的函数，创建闭包的最常见的方式就是在一个函数内创建另一个函数，通过另一个函数访问这个函数的局部变量</p>
<p>闭包的缺点就是常驻内存，会增大内存使用量，使用不当很容易造成内存泄露。</p>
<p>闭包是javascript语言的一大特点，主要应用闭包场合主要是为了：设计私有的方法和变量。</p>
<p>一般函数执行完毕后，局部活动对象就被销毁，内存中仅仅保存全局作用域。但闭包的情况不同！</p>
<h2 id="嵌套函数的闭包"><a href="#嵌套函数的闭包" class="headerlink" title="嵌套函数的闭包"></a>嵌套函数的闭包</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">function aaa() &#123;  </span><br><span class="line">  var a = 1;  </span><br><span class="line">  return function()&#123;</span><br><span class="line">   alert(a++)</span><br><span class="line">  &#125;;  </span><br><span class="line">&#125;         </span><br><span class="line">var fun = aaa();  </span><br><span class="line">fun();// 1 执行后 a++，，然后a还在~  </span><br><span class="line">fun();// 2   </span><br><span class="line">fun = null;//a被回收！！</span><br></pre></td></tr></table></figure>
<p>闭包会使变量始终保存在内存中，如果不当使用会增大内存消耗。</p>
<h2 id="javascript的垃圾回收原理"><a href="#javascript的垃圾回收原理" class="headerlink" title="javascript的垃圾回收原理"></a>javascript的垃圾回收原理</h2><ol>
<li>在javascript中，如果一个对象不再被引用，那么这个对象就会被GC回收； </li>
<li>如果两个对象互相引用，而不再被第3者所引用，那么这两个互相引用的对象也会被回收。</li>
</ol>
<a id="more"></a>
<h2 id="使用闭包的好处"><a href="#使用闭包的好处" class="headerlink" title="使用闭包的好处"></a>使用闭包的好处</h2><p>那么使用闭包有什么好处呢？使用闭包的好处是：</p>
<ol>
<li>希望一个变量长期驻扎在内存中</li>
<li>避免全局变量的污染</li>
<li>私有成员的存在</li>
</ol>
<h2 id="一、全局变量的累加"><a href="#一、全局变量的累加" class="headerlink" title="一、全局变量的累加"></a>一、全局变量的累加</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">&lt;script&gt;</span><br><span class="line">var a = 1;</span><br><span class="line">function abc()&#123;</span><br><span class="line">        a++;</span><br><span class="line">        alert(a);</span><br><span class="line">&#125;</span><br><span class="line">abc();              //2</span><br><span class="line">abc();            //3</span><br><span class="line">&lt;/script&gt;</span><br></pre></td></tr></table></figure>
<h2 id="二、局部变量"><a href="#二、局部变量" class="headerlink" title="二、局部变量"></a>二、局部变量</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">&lt;script&gt;</span><br><span class="line">function abc()&#123;</span><br><span class="line">        var a = 1;</span><br><span class="line">        a++;</span><br><span class="line">        alert(a);</span><br><span class="line">&#125;</span><br><span class="line">abc();                       //2</span><br><span class="line">abc();                    //2</span><br><span class="line">&lt;/script&gt;</span><br></pre></td></tr></table></figure>
<h2 id="三、局部变量的累加"><a href="#三、局部变量的累加" class="headerlink" title="三、局部变量的累加"></a>三、局部变量的累加</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">&lt;script&gt;</span><br><span class="line">function outer()&#123;</span><br><span class="line">        var x=10;</span><br><span class="line">        return function()&#123;             //函数嵌套函数</span><br><span class="line">                x++;</span><br><span class="line">                alert(x);</span><br><span class="line">        &#125;</span><br><span class="line">&#125;</span><br><span class="line">var y = outer();              //外部函数赋给变量y;</span><br><span class="line">y();                 //y函数调用一次，结果为11，相当于outer()()；</span><br><span class="line">y();                //y函数调用第二次，结果为12，实现了累加</span><br><span class="line">&lt;/script&gt;</span><br></pre></td></tr></table></figure>
<h2 id="函数声明与函数表达式"><a href="#函数声明与函数表达式" class="headerlink" title="函数声明与函数表达式"></a>函数声明与函数表达式</h2><p>在js中我们可以通过关键字function来声明一个函数：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">&lt;script&gt;</span><br><span class="line">function abc()&#123;</span><br><span class="line">        alert(123);</span><br><span class="line">&#125;</span><br><span class="line">abc();</span><br><span class="line">&lt;/script&gt;</span><br></pre></td></tr></table></figure>
<p>我们也可以通过一个”()”来将这个声明变成一个表达式：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">&lt;script&gt;</span><br><span class="line">(function ()&#123;</span><br><span class="line">        alert(123);</span><br><span class="line">&#125;)();                   //然后通过()直接调用前面的表达式即可，因此函数可以不必写名字；</span><br><span class="line">&lt;/script&gt;</span><br></pre></td></tr></table></figure>
<h2 id="四、模块化代码，减少全局变量的污染"><a href="#四、模块化代码，减少全局变量的污染" class="headerlink" title="四、模块化代码，减少全局变量的污染"></a>四、模块化代码，减少全局变量的污染</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">&lt;script&gt;</span><br><span class="line">var abc = (function()&#123;      //abc为外部匿名函数的返回值</span><br><span class="line">        var a = 1;</span><br><span class="line">        return function()&#123;</span><br><span class="line">                a++;</span><br><span class="line">                alert(a);</span><br><span class="line">        &#125;</span><br><span class="line">&#125;)();</span><br><span class="line">abc();    //2 ；调用一次abc函数，其实是调用里面内部函数的返回值    </span><br><span class="line">abc();    //3</span><br><span class="line">&lt;/script&gt;</span><br></pre></td></tr></table></figure>
<h2 id="五、私有成员的存在"><a href="#五、私有成员的存在" class="headerlink" title="五、私有成员的存在"></a>五、私有成员的存在</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line">&lt;script&gt;</span><br><span class="line">var aaa = (function()&#123;</span><br><span class="line">    var a = 1;</span><br><span class="line">    function bbb()&#123;</span><br><span class="line">            a++;</span><br><span class="line">            alert(a);</span><br><span class="line">    &#125;</span><br><span class="line">    function ccc()&#123;</span><br><span class="line">            a++;</span><br><span class="line">            alert(a);</span><br><span class="line">    &#125;</span><br><span class="line">    return &#123;</span><br><span class="line">            b:bbb,             //json结构</span><br><span class="line">            c:ccc</span><br><span class="line">    &#125;</span><br><span class="line">&#125;)();</span><br><span class="line">aaa.b();     //2</span><br><span class="line">aaa.c()      //3</span><br><span class="line">&lt;/script&gt;</span><br></pre></td></tr></table></figure>
<h2 id="六-使用匿名函数实现累加"><a href="#六-使用匿名函数实现累加" class="headerlink" title="六.使用匿名函数实现累加"></a>六.使用匿名函数实现累加</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line">//使用匿名函数实现局部变量驻留内存中，从而实现累加</span><br><span class="line">&lt;script type=&quot;text/javascript&quot;&gt;</span><br><span class="line"> function box()&#123;</span><br><span class="line">     var age = 100;</span><br><span class="line">     return function()&#123;          //匿名函数</span><br><span class="line">          age++;</span><br><span class="line">          return age;</span><br><span class="line">     &#125;;</span><br><span class="line"> &#125; </span><br><span class="line">var b = box();</span><br><span class="line">alert(b());</span><br><span class="line">alert(b());    //即alert(box()())；</span><br><span class="line">alert(b());</span><br><span class="line">alert(b);            //     function () &#123;</span><br><span class="line">                        //   age++;</span><br><span class="line">                       // return age;</span><br><span class="line">                      //       &#125;</span><br><span class="line">b = null；  //解除引用，等待垃圾回收</span><br><span class="line">&lt;/script&gt;</span><br></pre></td></tr></table></figure>
<p>过度使用闭包会导致性能的下降。函数里放匿名函数，则产生了闭包</p>
<h2 id="七、在循环中直接找到对应元素的索引"><a href="#七、在循环中直接找到对应元素的索引" class="headerlink" title="七、在循环中直接找到对应元素的索引"></a>七、在循环中直接找到对应元素的索引</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line">&lt;!DOCTYPE html PUBLIC &quot;-//W3C//DTD XHTML 1.0 Transitional//EN&quot; </span><br><span class="line">&quot;http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd&quot;&gt;</span><br><span class="line">    &lt;html xmlns=&quot;http://www.w3.org/1999/xhtml&quot; xml:lang=&quot;en&quot;&gt;</span><br><span class="line">    &lt;head&gt;</span><br><span class="line">            &lt;meta http-equiv=&quot;Content-Type&quot; content=&quot;text/html;charset=UTF-8&quot; /&gt;</span><br><span class="line">            &lt;title&gt;&lt;/title&gt;</span><br><span class="line">    &lt;script&gt;</span><br><span class="line">    window.onload = function()&#123;</span><br><span class="line">            var aLi = document.getElementsByTagName(&apos;li&apos;);</span><br><span class="line">            for (var i=0;i&lt;aLi.length;i++)&#123;</span><br><span class="line">                    aLi[i].onclick = function()&#123;        //当点击时for循环已经结束</span><br><span class="line">                    alert(i);</span><br><span class="line">                    &#125;;</span><br><span class="line">            &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    &lt;/script&gt;        </span><br><span class="line">    &lt;/head&gt;</span><br><span class="line">    &lt;body&gt;</span><br><span class="line">            &lt;ul&gt;</span><br><span class="line">                    &lt;li&gt;123&lt;/li&gt;</span><br><span class="line">                    &lt;li&gt;456&lt;/li&gt;</span><br><span class="line">                    &lt;li&gt;789&lt;/li&gt;</span><br><span class="line">                    &lt;li&gt;010&lt;/li&gt;</span><br><span class="line">            &lt;/ul&gt;</span><br><span class="line">    &lt;/body&gt;</span><br><span class="line">    &lt;/html&gt;</span><br></pre></td></tr></table></figure>
<h2 id="八、使用闭包改写上面代码"><a href="#八、使用闭包改写上面代码" class="headerlink" title="八、使用闭包改写上面代码"></a>八、使用闭包改写上面代码</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><span class="line">&lt;!DOCTYPE html PUBLIC &quot;-//W3C//DTD XHTML 1.0 Transitional//EN&quot; </span><br><span class="line">&quot;http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd&quot;&gt;</span><br><span class="line">    &lt;html xmlns=&quot;http://www.w3.org/1999/xhtml&quot; xml:lang=&quot;en&quot;&gt;</span><br><span class="line">    &lt;head&gt;</span><br><span class="line">            &lt;meta http-equiv=&quot;Content-Type&quot; content=&quot;text/html;charset=UTF-8&quot; /&gt;</span><br><span class="line">            &lt;title&gt;&lt;/title&gt;</span><br><span class="line">    &lt;script&gt;</span><br><span class="line">    window.onload = function()&#123;</span><br><span class="line">            var aLi = document.getElementsByTagName(&apos;li&apos;);</span><br><span class="line">            for (var i=0;i&lt;aLi.length;i++)&#123;</span><br><span class="line">                    (function(i)&#123;</span><br><span class="line">                            aLi[i].onclick = function()&#123;</span><br><span class="line">                                    alert(i);</span><br><span class="line">                            &#125;;</span><br><span class="line">                    &#125;)(i);</span><br><span class="line">            &#125;</span><br><span class="line">            &#125;;</span><br><span class="line">    &lt;/script&gt;  </span><br><span class="line">    &lt;/head&gt;</span><br><span class="line">    &lt;body&gt;</span><br><span class="line">            &lt;ul&gt;</span><br><span class="line">                    &lt;li&gt;123&lt;/li&gt;</span><br><span class="line">                    &lt;li&gt;456&lt;/li&gt;</span><br><span class="line">                    &lt;li&gt;789&lt;/li&gt;</span><br><span class="line">            &lt;/ul&gt;</span><br><span class="line">    &lt;/body&gt;</span><br><span class="line">    &lt;/html&gt;</span><br></pre></td></tr></table></figure>
<h2 id="九-内存泄露问题"><a href="#九-内存泄露问题" class="headerlink" title="九.内存泄露问题"></a>九.内存泄露问题</h2><p>由于IE的js对象和DOM对象使用不同的垃圾收集方法，因此闭包在IE中会导致内存泄露问题，也就是无法销毁驻留在内存中的元素</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line">function closure()&#123;</span><br><span class="line">    var oDiv = document.getElementById(&apos;oDiv&apos;);//oDiv用完之后一直驻留在内存中</span><br><span class="line">    oDiv.onclick = function () &#123;</span><br><span class="line">        alert(&apos;oDiv.innerHTML&apos;);//这里用oDiv导致内存泄露</span><br><span class="line">    &#125;;</span><br><span class="line">&#125;</span><br><span class="line">closure();</span><br><span class="line">//最后应将oDiv解除引用来避免内存泄露</span><br><span class="line">function closure()&#123;</span><br><span class="line">    var oDiv = document.getElementById(&apos;oDiv&apos;);</span><br><span class="line">    var test = oDiv.innerHTML;</span><br><span class="line">    oDiv.onclick = function () &#123;</span><br><span class="line">        alert(test);</span><br><span class="line">    &#125;;</span><br><span class="line">    oDiv = null;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>参考资料：</p>
<p><a href="https://segmentfault.com/a/1190000000652891" target="_blank" rel="noopener">详解js闭包</a></p>
<p><a href="http://www.ruanyifeng.com/blog/2009/08/learning_javascript_closures.html" target="_blank" rel="noopener">学习Javascript闭包</a></p>
<p><a href="http://www.cnblogs.com/pp-cat/p/4384610.html" target="_blank" rel="noopener">javascript闭包的理解</a></p>
      
    </div>
    
    
    

    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center">
  <div>Donate comment here</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="/images/wechatpay.jpg" alt="Tony 微信支付">
        <p>微信支付</p>
      </div>
    

    
      <div id="alipay" style="display: inline-block">
        <img id="alipay_qr" src="/images/alipay.jpg" alt="Tony 支付宝">
        <p>支付宝</p>
      </div>
    

    

  </div>
</div>

      </div>
    

    

    <footer class="post-footer">
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2013/04/08/javascript原型与原型链/" rel="next" title="JavaScript原型与原型链">
                <i class="fa fa-chevron-left"></i> JavaScript原型与原型链
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2013/04/09/类型判断/" rel="prev" title="类型判断">
                类型判断 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <p class="site-author-name" itemprop="name">Tony</p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives">
              
                  <span class="site-state-item-count">65</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">18</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">3</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          

          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#闭包的特性"><span class="nav-number">1.</span> <span class="nav-text">闭包的特性</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#闭包的定义及其优缺点"><span class="nav-number">2.</span> <span class="nav-text">闭包的定义及其优缺点</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#嵌套函数的闭包"><span class="nav-number">3.</span> <span class="nav-text">嵌套函数的闭包</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#javascript的垃圾回收原理"><span class="nav-number">4.</span> <span class="nav-text">javascript的垃圾回收原理</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#使用闭包的好处"><span class="nav-number">5.</span> <span class="nav-text">使用闭包的好处</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#一、全局变量的累加"><span class="nav-number">6.</span> <span class="nav-text">一、全局变量的累加</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#二、局部变量"><span class="nav-number">7.</span> <span class="nav-text">二、局部变量</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#三、局部变量的累加"><span class="nav-number">8.</span> <span class="nav-text">三、局部变量的累加</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#函数声明与函数表达式"><span class="nav-number">9.</span> <span class="nav-text">函数声明与函数表达式</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#四、模块化代码，减少全局变量的污染"><span class="nav-number">10.</span> <span class="nav-text">四、模块化代码，减少全局变量的污染</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#五、私有成员的存在"><span class="nav-number">11.</span> <span class="nav-text">五、私有成员的存在</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#六-使用匿名函数实现累加"><span class="nav-number">12.</span> <span class="nav-text">六.使用匿名函数实现累加</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#七、在循环中直接找到对应元素的索引"><span class="nav-number">13.</span> <span class="nav-text">七、在循环中直接找到对应元素的索引</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#八、使用闭包改写上面代码"><span class="nav-number">14.</span> <span class="nav-text">八、使用闭包改写上面代码</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#九-内存泄露问题"><span class="nav-number">15.</span> <span class="nav-text">九.内存泄露问题</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; 2015 &mdash; <span itemprop="copyrightYear">2018</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Tony</span>

  
</div>


  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Gemini</a> v5.1.4</div>




        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  


  



  
  









  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  

  
  
    <script type="text/javascript" src="/lib/canvas-nest/canvas-nest.min.js"></script>
  

  
  
    <script type="text/javascript" src="/lib/three/three.min.js"></script>
  

  
  
    <script type="text/javascript" src="/lib/three/three-waves.min.js"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  





  

  

  

  
  

  

  

  

</body>
</html>